package com.siruier.boss.ui.activity.mall

import android.view.View
import androidx.core.view.isVisible
import com.kingja.loadsir.core.LoadService
import com.siruier.boss.R
import com.siruier.boss.api.MALL_API_SERVICE
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.loginApi
import com.siruier.boss.api.mallApi
import com.siruier.boss.bean.MallGoodsBean
import com.siruier.boss.bean.OrderDetailBean
import com.siruier.boss.bean.ShopAddressBean
import com.siruier.boss.bean.UserLevelEnum
import com.siruier.boss.common.formatPrice
import com.siruier.boss.common.formatPriceRmb
import com.siruier.boss.databinding.ActivityConfirmOrderBinding
import com.siruier.boss.ui.adapter.ConfirmOrderShopAdapter
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.cache.UserCache
import com.siruier.boss.ui.dialog.InputDialog
import com.siruier.boss.ui.ext.*
import com.siruier.boss.ui.helper.InjectBundle
import com.siruier.boss.ui.helper.checkPay
import com.siruier.boss.ui.helper.loadsir.LoadSirHelper
import com.siruier.boss.ui.helper.pay
import com.siruier.boss.ui.helper.payChannel
import com.siruier.boss.ui.utils.FullyLinearLayoutManager
import com.siruier.boss.ui.utils.Logger
import com.siruier.boss.ui.utils.SPUtils
import java.math.BigDecimal

class ConfirmOrderActivity : BaseActivity<ActivityConfirmOrderBinding>() {
    private val mLoadService: LoadService<*> by lazy { LoadSirHelper.register(vb.rootView) { onReload() } }
    private val mConfirmOrderShopAdapter: ConfirmOrderShopAdapter = ConfirmOrderShopAdapter()
    private var mShopAddressBean: ShopAddressBean? = null
    private val type: Int by InjectBundle()
    private val mGoodsId: Int by InjectBundle()
    private val mGoodsNum: Int by InjectBundle()
    private val mGoodsSpecnId: String by InjectBundle()
    private val mGoods: MallGoodsBean by InjectBundle()
    private lateinit var mOrderDetailBean: OrderDetailBean
    private var mOrderDetailSubmitBean: OrderDetailBean? = null
    private var discount: BigDecimal = BigDecimal("0.0")

    // 订单类型 1-自购订单 2-赠送订单
    private var orderType: Int = 1

    override fun initView() {
        bindViewClick(vb.viewAddessClick, vb.buttonSubmitOrder, vb.rbSelfUse, vb.rbPassOn)
        mConfirmOrderShopAdapter.setOnClickAdapterListenter(this::onClick)
        vb.rvOrder.adapter = mConfirmOrderShopAdapter
        vb.rvOrder.layoutManager = FullyLinearLayoutManager(this)
        vb.llRb.isVisible = type !in 5..6
        // 如果是门店商品，用户身份不是boss+门店认证的，隐藏这个选项
        if (type == 3) {
            vb.llRb.isVisible = false
        }
    }

    override fun initData() {
        mLoadService.showLoadingCallback()
        onReload()
    }

    private fun onReload() {
        launchUI({
            changeAddress(mallApi.addressGetDefault().toData())
            // 如果是门店商品，用户身份不是boss+门店认证的，隐藏这个选项
            if (type == 3) {
                UserCache.saveUserInfoBean(loginApi.userInfo().toData())
                UserCache.getUserInfoBean().let { user ->
                    if (user.userLevel == UserLevelEnum.BOSS.level &&
                        user.type == 2 &&
                        user.authStatus == 1
                    ) {
                        vb.llRb.isVisible = true
                    }
                }
            }
            // 加盟区门店商品转赠的时候增加一个预抵扣
            if (type in 2..3) {
                discount = mallApi.discount(mGoodsId, null, mGoodsSpecnId).toData()?.discount
                    ?: BigDecimal.ZERO
            }
            mallApi.orderPreview(mGoodsId, mGoodsNum, mGoodsSpecnId).toData()?.apply {
                mOrderDetailBean = this
                val orderPrice = orderPrice.add(freightPrice)
                vb.tvPrice.text = orderPrice.formatPrice()
                mConfirmOrderShopAdapter.datas = mutableListOf(this)
                mConfirmOrderShopAdapter.notifyDataSetChanged()

                val orderSn = SPUtils.getString("orderSn")
                if (orderSn.isNotEmpty()) {
                    // 有未处理的订单，查询支付状态，不管成功与否都跳转详情页
                    checkPay(orderSn)
                    SPUtils.remove("orderSn")
                    startActivityExt<UserOrderDetailsActivity> {
                        putExtra("mOrderSn", orderSn)
                    }
                    finish()
                }
            }
        }, ApiObserver(loadService = mLoadService))
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.rbSelfUse -> {
                orderType = 1
                vb.clAddress.isVisible = true
                vb.tvPrice.text =
                    mOrderDetailBean.orderPrice.plus(mOrderDetailBean.freightPrice).formatPrice()
                vb.tvDiscountPrice.text = ""
            }
            vb.rbPassOn -> {
                orderType = 2
                vb.clAddress.isVisible = false
                vb.tvPrice.text =
                    mOrderDetailBean.orderPrice.minus(discount).plus(mOrderDetailBean.freightPrice)
                        .formatPrice()
                vb.tvDiscountPrice.text = "(预抵扣${discount.formatPriceRmb()})"
            }
            vb.viewAddessClick -> launchStartActivityForResult(
                ReceivingAddressActivity::class.java,
                options = { putBoolean(ReceivingAddressActivity.CLICK_FINISH, true) }) {
                changeAddress(it.data?.getParcelableExtra(ReceivingAddressActivity.RECEIVING_ADDRESS))
            }
            vb.buttonSubmitOrder -> {
                if (orderType == 1 && mShopAddressBean == null) {
                    "请选择地址".toastMessageLong()
                    return
                }
                orderSubmit()
            }
        }
    }

    private fun onClick(view: View, position: Int) {
        if (R.id.tvNote == view.id) {
            val item = mConfirmOrderShopAdapter.getItem(position)
            InputDialog(this, "订单备注", "请输入订单备注", item.comment) {
                item.comment = it
                mConfirmOrderShopAdapter.notifyItemChanged(
                    position,
                    ConfirmOrderShopAdapter.UPDATE_NOTE_PAYLOAD
                )
            }.show()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        SPUtils.remove("orderSn")
    }

    private fun orderSubmit() {
        mOrderDetailBean.apply {
            launchUI(
                {
                    val payModel = payChannel(
                        orderPrice.add(freightPrice),
                        if (orderType == 2) discount else BigDecimal.ZERO
                    )
                    // 下单
                    mOrderDetailSubmitBean = mallApi.orderSubmit(
                        mShopAddressBean?.id, comment, mGoodsId, null,
                        mGoodsNum, mGoodsSpecnId, orderType
                    ).toData()
                    payModel.orderSn = mOrderDetailSubmitBean?.orderSn
                    SPUtils.put("orderSn", payModel.orderSn!!)
                    // 支付
                    val payResult = pay(payModel)
                    if (payResult) {
                        openUserOrderDetails(payResult, payModel.orderPrice)
                    } else {
                        openUserOrderDetails(false, null)
                    }
                }, ApiObserver(mThis, commonButton = vb.buttonSubmitOrder,
                    complete = {
                        SPUtils.remove("orderSn")
                    },
                    error = {
                        openUserOrderDetails(false, null)
                    })
            )
        }
    }

    private fun openUserOrderDetails(payResult: Boolean?, orderPrice: BigDecimal?) {
        mOrderDetailSubmitBean?.let { orderDetailSubmitBean ->
            if (payResult == true) {
                startActivityExt<OrderPaySuccessActivity> {
                    putExtra("passOn", vb.rbPassOn.isChecked)
                    putExtra("picUrl", mConfirmOrderShopAdapter.getItem(0).goodsList[0].picUrl)
                    putExtra("mOrderSn", orderDetailSubmitBean.orderSn)
                    putExtra("mOrderPrice", orderPrice)
                    putExtra("mGoods", mGoods)
                    putExtra("type", this@ConfirmOrderActivity.type)
                }
            } else {
                startActivityExt<UserOrderDetailsActivity> {
                    putExtra("mOrderSn", orderDetailSubmitBean.orderSn)
                }
            }
            finish()
        }
    }

    private fun changeAddress(shopAddressBean: ShopAddressBean?) {
        mShopAddressBean = shopAddressBean
        mShopAddressBean?.run {
            vb.viewAddressEmpty.gone()
            vb.groupAddress.visible()
            vb.tvName.text = name
            vb.tvPhome.text = phone
            vb.tvAddressDetails.text = province + city + county + address
        }
    }
}